package com.mask.order.controller;


import com.mask.order.service.PayLogService;
import com.mask.roll.common.code.ServiceEnums;
import com.mask.roll.common.constant.RollConstants;
import com.mask.roll.common.util.RollResponse;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 支付日志表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-03-13
 */
@RestController
@RequestMapping("/order/pay")
@CrossOrigin
@Slf4j
@Api(tags = "订单支付管理")
public class PayLogController {

    @Autowired
    private PayLogService payLogService;

    //生成微信支付二维码接口
    //参数是订单号
    @GetMapping("/create/native/{orderNo}")
    public RollResponse createNative(@PathVariable String orderNo) {
        //返回信息，包含二维码地址，还有其他需要的信息
        Map map = payLogService.createNatvie(orderNo);
        log.info("订单号{}生成二维码集合:{}",orderNo,map);
        return RollResponse.result(ServiceEnums.ORDER_CREATE_NATIVE_SUCCESS.getCode(),
                RollConstants.SUCCESS,ServiceEnums.ORDER_CREATE_NATIVE_SUCCESS.getMessage(),map);
    }

    //查询订单支付状态
    //参数：订单号，根据订单号查询 支付状态
    @GetMapping("/query/status/{orderNo}")
    public RollResponse queryPayStatus(@PathVariable String orderNo) {
        Map<String,String> map = payLogService.queryPayStatus(orderNo);
        log.info("订单号{}状态:{}",orderNo,map);
        if(map == null) {
            return RollResponse.result(ServiceEnums.ORDER_PAY_STATE_FAILED.getCode(),
                    RollConstants.ERROR,RollConstants.ERROR,ServiceEnums.ORDER_PAY_STATE_FAILED.getMessage());
        }
        //如果返回map里面不为空，通过map获取订单状态
        //支付成功
        if(RollConstants.ORDER_PAY_SUCCESS.equals(map.get("trade_state"))) {
            //添加记录到支付表，更新订单表订单状态
            payLogService.updateOrdersStatus(map);
            return RollResponse.result(ServiceEnums.ORDER_PAY_STATE_SUCCESS.getCode(),
                    RollConstants.SUCCESS,ServiceEnums.ORDER_PAY_STATE_SUCCESS.getMessage());
        }
        return RollResponse.result(ServiceEnums.ORDER_PAY_STATE_NOW.getCode(),
                RollConstants.INFO,ServiceEnums.ORDER_PAY_STATE_NOW.getMessage());

    }
}

